<template>
  <div class="department-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>部门管理</span>
          <el-button type="primary" @click="handleAdd">新增部门</el-button>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="部门名称">
          <el-input v-model="queryForm.name" placeholder="请输入部门名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 部门列表 -->
      <el-table :data="departments" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="部门名称" width="150" />
        <el-table-column prop="fullPath" label="部门全路径" min-width="300" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 部门表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增部门' : '编辑部门'"
      width="500px"
      @closed="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="department-form"
      >
        <el-form-item label="父级部门" prop="parentId">
          <el-select
            v-model="form.parentId"
            :data="departmentTree"
            placeholder="请选择父级部门"
            clearable
            class="w-full"
          >
            <el-option
              v-for="dept in departmentTree"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入部门描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

interface Department {
  id: number
  name: string
  description: string
  parentId?: number
  parent?: Department
  children?: Department[]
  createdAt: string
  updatedAt: string
  fullPath?: string
}

// 查询表单
const queryForm = reactive({
  name: '',
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 部门列表数据
const departments = ref<Department[]>([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()

// 部门树形数据
const departmentTree = ref<Department[]>([])

// 表单数据
const form = reactive({
  id: 0,
  name: '',
  description: '',
  parentId: undefined as number | undefined,
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
})

const router = useRouter()

// 获取部门列表
const fetchDepartments = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/departments', {
      params: {
        name: queryForm.name || undefined,
      },
    })
    if (response.data) {
      // 处理部门数据，计算全路径
      departments.value = response.data.map((dept: any) => {
        // 使用后端返回的 fullPath
        return {
          ...dept,
          fullPath: dept.fullPath || dept.name,
        }
      })
      total.value = departments.value.length
    } else {
      ElMessage.error('返回数据格式不正确')
    }
  } catch (error: any) {
    console.error('获取部门列表失败:', error)
    if (error.response?.status === 401) {
      ElMessage.error('请先登录')
      router.push('/login')
    } else if (error.response?.status === 403) {
      ElMessage.error('没有权限访问')
    } else {
      ElMessage.error(error.response?.data?.message || '获取部门列表失败')
    }
  } finally {
    loading.value = false
  }
}

// 获取部门树形数据
const fetchDepartmentTree = async () => {
  try {
    const response = await axios.get('/api/departments')
    // 将所有部门转换为扁平结构，每个部门都显示其完整路径
    const allDepartments = response.data.map((dept: any) => {
      // 使用后端返回的 fullPath
      return {
        ...dept,
        name: dept.fullPath || dept.name,
      }
    })
    departmentTree.value = allDepartments
  } catch (error) {
    console.error('获取部门树失败:', error)
    ElMessage.error('获取部门树失败')
  }
}

// 查询
const handleQuery = () => {
  currentPage.value = 1
  fetchDepartments()
}

// 重置
const handleReset = () => {
  queryForm.name = ''
  handleQuery()
}

// 新增部门
const handleAdd = () => {
  dialogType.value = 'add'
  form.id = 0
  form.name = ''
  form.description = ''
  form.parentId = undefined
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (row: Department) => {
  dialogType.value = 'edit'
  form.id = row.id
  form.name = row.name
  form.description = row.description
  // 不能选择自己或自己的子部门作为父级
  const currentDepartment = departmentTree.value.find((d) => d.id === row.id)
  if (currentDepartment) {
    departmentTree.value = departmentTree.value.filter((d) => d.id !== row.id)
  }
  form.parentId = row.parent?.id
  dialogVisible.value = true
}

// 删除部门
const handleDelete = (row: Department) => {
  ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await axios.delete(`/api/departments/${row.id}`)
      // 记录删除日志
      await axios.post('/api/logs', {
        action: 'DELETE_DEPARTMENT',
        description: `删除部门：${row.name}`,
      })
      ElMessage.success('删除成功')
      fetchDepartments()
    } catch (error) {
      console.error('删除部门失败:', error)
      ElMessage.error('删除部门失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          name: form.name,
          description: form.description,
          parentId: form.parentId ? form.parentId : null,
        }

        if (dialogType.value === 'add') {
          await axios.post('/api/departments', submitData)
          // 记录创建日志
          await axios.post('/api/logs', {
            action: 'CREATE_DEPARTMENT',
            description: `创建部门：${form.name}`,
          })
          ElMessage.success('新增成功')
        } else {
          await axios.put(`/api/departments/${form.id}`, submitData)
          // 记录更新日志
          await axios.post('/api/logs', {
            action: 'UPDATE_DEPARTMENT',
            description: `更新部门：${form.name}`,
          })
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchDepartments()
      } catch (error: any) {
        console.error('保存部门失败:', error)
        const errorMsg = error.response?.data?.message
        if (
          errorMsg?.includes('Duplicate entry') ||
          errorMsg?.includes('UK_j6cwks7xecs5jov19ro8ge3qk')
        ) {
          ElMessage.error('部门名称已存在，请使用其他名称')
        } else {
          ElMessage.error(errorMsg || '保存部门失败')
        }
      }
    }
  })
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchDepartments()
}

// 页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchDepartments()
}

// 关闭对话框时恢复部门树数据
const handleDialogClose = () => {
  fetchDepartmentTree()
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: '访问部门管理页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

// 初始化
onMounted(() => {
  fetchDepartments()
  fetchDepartmentTree()
  recordPageAccess()
})
</script>

<style scoped>
.department-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #f56c6c;
}

.department-form {
  padding: 20px;
}
</style>
